package mBio;

import java.io.*;
import java.util.*;
import rfBio.*;

public class getRegion{

	public static void main(String[] args)
		throws IOException, FileNotFoundException{
			
		if(args.length != 4){
			System.out.println("Wrong number of parameters!" + '\n' + "Usage: getRegion genFile estFile minScore outFile.");
			System.exit(0);
		}

		// local variables
		Vector gene_vector = new Vector(100,100); 
		Vector est_vector = new Vector(1000,1000);
		boolean addFlag = true;
		psl3 nov = new psl3();
		


		BufferedReader genFile = new BufferedReader ( new FileReader (args[0]));
		
		// read gen_file line by line, store in gene_vector
		while (true){
			String line = genFile.readLine();
			if (line == null)
			{
				break;
			}
			psl3 temp_psl3 = new psl3(line);
			//System.out.println(line);
			if( (temp_psl3.get_score() <= Type.toInt(args[2])) )
			{
				addFlag=false;
			}
			
			if(addFlag){
				for(int i =0; i < gene_vector.size(); i++){
					psl3 tmp = new psl3((psl3) gene_vector.get(i));
					if(temp_psl3.get_Q_name().equals(tmp.get_Q_name())){
						if( (temp_psl3.get_score() >= tmp.get_score())){			
							gene_vector.set(i, temp_psl3);
							addFlag=false;
						}
						else{
							addFlag=false;
						}	
					}
				}
			}

			if(addFlag){
				gene_vector.add(temp_psl3);
			}
			
			addFlag=true;
		} 		

		// close gene_ file
		genFile.close();
		
		
		psl3 t = new psl3( (psl3)(gene_vector.get(0)));
		String gene_name = t.get_Q_name();
		String ch_name = t.get_T_name();
		int start = t.get_T_start();
		int end = t.get_T_end();
		
		System.out.println("Read " + gene_name + " from " +  args[0] + "." );
		
		//Read EST_file line by line and store the required ESTs
		BufferedReader estFile = new BufferedReader ( new FileReader (args[1]));
		
		while (true){
			String line = estFile.readLine();
			if (line == null)
			{
				break;
			}
			psl3 temp_psl3 = new psl3(line);
			//System.out.println(line);
			if( (temp_psl3.get_score() <= Type.toInt(args[2])) )
			{
				addFlag=false;
			}
			
			if( temp_psl3.get_Q_name() != ch_name){
				addFlag=false;
			}
			
			if( !((temp_psl3.get_T_start() >= start) && (temp_psl3.get_T_end() <= end))  ){
				addFlag=false;
			}
			
			if(addFlag){
				est_vector.add(temp_psl3);	
			}
			addFlag=true;
		} 		

		// close ref_ file
		genFile.close();
		//write output files
		
		PrintWriter o_file = new PrintWriter(new BufferedWriter(new FileWriter(args[3])));
				
		for(int i =0; i < est_vector.size(); i++)
		{
			nov = (psl3) est_vector.get(i);
			o_file.println(nov.export());
		}
		
		o_file.close();

   }
}